package com.vsd.mobile;




import java.util.Date;
import java.util.UUID;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.demo.annotation.LoginFilter;
import com.demo.annotation.MobileMethod;
import com.demo.cache.CacheSupport;
import com.demo.mobile.MFrameEnumError;
import com.demo.mobile.MobException;
import com.demo.mobile.MobileInfo;
import com.demo.service.MobileVerifyService;
import com.demo.util.DXWSMSUtils;
import com.demo.util.ProperityUtil;
import com.demo.util.Sendsms;
import com.demo.validator.MobileLoginValidate;
import com.shopcart.domain.Store;
import com.vsd.domain.City;
import com.vsd.domain.User;
import com.vsd.domain.UserCollect;
import com.vsd.mobile.error.MEnumError;
import com.vsd.repository.UserCollectionRepository;
import com.vsd.service.StoreService;
import com.vsd.service.UserService;
import com.zy.account.proto.MUserAccount.MAccount;
import com.zy.account.proto.MUserAccount.MUserInfo;
import com.zy.sys.proto.MOCommon.MRet;

@Controller
@RequestMapping("/mobile/")
public class MUserAccountController {
	
	@Autowired
	private UserService userService;
	@Autowired
	private ProperityUtil properity;
	@Autowired
	private StoreService storeService;
	@Autowired
	private MobileVerifyService mobileVerifyService;
	@Autowired
	private UserCollectionRepository userCollectionRepository;
	@Autowired
	private ProperityUtil properityUtil;
	
	/**
	 * 获取验证码
	 * @param phone 手机号
	 * @param type 1:注册,绑定手机  2:忘记密码 3:邀请好友
	 * @url /mobile?methodno=MGetMobileMsg&debug=1&deviceid=test&phone=&type=
	 */
	@RequestMapping("/mGetMobileMsg")
	@MobileMethod
	public MRet.Builder getMobileMsg(MobileInfo mobileInfo, String phone, Integer type) throws Exception {
		// 参数校验
		if (StringUtils.isBlank(phone)) {
			throw new MobException("phone");
		}
		if (type == null) {
			throw new MobException("type");
		}
		if(type==3&&StringUtils.isBlank(mobileInfo.getUserid())){
			throw new MobException(MFrameEnumError.LOGIN_FAIL_ERROR);
		}
		// 查询
		int count = 0;
		if(mobileInfo.getDeviceid().endsWith("@store")){
			Page<Store> stores = storeService.findByPhone(phone,new PageRequest(0, 1));
			count = stores.getContent().size();
		}else{
			Page<User> users = userService.findByPhone(phone,new PageRequest(0, 1));
			count = users.getContent().size();
		}
		

		if (type == 1) {// 注册
			if (count > 0) {
				throw new MobException(MEnumError.PHONE_EXIST_ERROR);
			}
		} else if(type==2){
			if (count == 0) {
				throw new MobException(MEnumError.PHONE_NOTEXISTS_ERROR);
			}
		}else if(type==3){
			if(count==0){
				throw new MobException(MEnumError.PHONE_NOTEXISTS_ERROR);
			}
		}
		
		// 发送短信
		int mobileCode = (int) ((Math.random() * 9 + 1) * 100000);
		String content = new String("您的验证码是：" + mobileCode + "。请不要把验证码泄露给其他人。");
		if(type==3){
			User u = userService.findByPrimaryKey(mobileInfo.getUserid());
			content = "您的朋友"+u.getPhone()+"邀请您注册【蹭一族】";
		}
		System.out.println(content);
		
		// 返回
		MRet.Builder ret = MRet.newBuilder();
		
		CacheSupport.put("mobileCodeCache", phone, mobileCode + "");
		ret.setCode(0);
		ret.setMsg(mobileCode+"");
		
		Sendsms code = DXWSMSUtils.push(phone, content);
		if(code==null||!code.getCode().equals("0")){
			CacheSupport.remove("mobileCodeCache", phone);
			throw new MobException(Integer.parseInt(code.getCode()),code.getMsg());
		}
		return ret;
	}

	/**
	 * 验证验证码
	 * @param phone 手机号
	 * @param code 验证码
	 * @url /mobile?methodno=MCheckMobileMsg&debug=1&deviceid=test&phone=&code=
	 */
	@RequestMapping("/MCheckMobileMsg")
	@MobileMethod
	public MRet.Builder checkMobileMsg(MobileInfo mobileInfo, String phone, String code) throws Exception {
		// 参数校验
		if (StringUtils.isBlank(phone)) {
			throw new MobException("phone");
		}
		if (StringUtils.isBlank(code)) {
			throw new MobException("code");
		}
		MRet.Builder ret = MRet.newBuilder();

		String value = CacheSupport.get("mobileCodeCache", phone, String.class);
//		// 返回
		if (code.equals(value)) {
			ret.setCode(0);
		} else {
			ret.setCode(1);
		}
		return ret;
	}

	/**
	 * 注册
	 * @param phone 手机号
	 * @param code 验证码
	 * @param password 密码(需要加密)
	 * @param device //设备类型  android或ios
	 * @param cid //个推cid
	 * @param inviteCode //邀请码
	 * @url /mobile?methodno=MRegist&debug=1&deviceid=test&phone=&code=&password=&device=&recommedCode=
	 */
	@RequestMapping("/mRegist")
	@MobileMethod
	public MAccount.Builder regist(MobileInfo mobileInfo, String phone, 
			String code, String password,String recommend, String device,String cid) throws Exception {
		// 参数校验
		if (StringUtils.isBlank(phone)) {
			throw new MobException("phone");
		}
		if (StringUtils.isBlank(code)) {
			throw new MobException("code");
		}
		if (StringUtils.isBlank(password)) {
			throw new MobException("password");
		}
		if (StringUtils.isBlank(device)) {
			throw new MobException("device");
		}
		
		
		//验证码验证
		String value = CacheSupport.get("mobileCodeCache", phone, String.class);
		if(!code.equals(value)){
			throw new MobException(MEnumError.MOBILE_CODE_ERROR);
		}
		
		
		int i = userService.countByAccount(phone);
		if(i>0){
			throw new MobException(MEnumError.PHONE_EXIST_ERROR);
		}
		
		 
		
//		//添加数据
		User record = new User();
		record.setUsername(phone);
		record.setCreateTime(new Date());
		record.setState(1);
		record.setPassword(password);
		record.setNickName("匿名用户");
		record.setSex(0);
		record.setBannedPost(0);
		record.setCredit(0);
		record.setEnabled(1);
		record = userService.save(record);
		if(record == null){
			throw new MobException(MEnumError.CREATE_ACCOUNT_ERROR);
		}
		mobileInfo.setUserid(record.getId()+"");
		String verify = mobileVerifyService.updateMobileVerify(mobileInfo, device, cid, true);
		
		// 返回
		MAccount.Builder ret = MAccount.newBuilder();
		ret.setId(record.getId()+"");
		ret.setVerify(verify);
		return ret;
	}

	/**
	* @api 登录
	* @param phone 手机号
	* @param password 密码(需要加密)
	* @param device 设备类型  android或ios
	* @param cid //个推cid
	* @url /mobile?methodno=MLogin&debug=1&deviceid=test&phone=&password=&device=
	*/
	@RequestMapping("mLogin")
	@MobileMethod
	public MAccount.Builder login(MobileInfo mobileInfo,String phone, String password, String device, String cid) throws Exception {
		// 参数校验
		if (StringUtils.isBlank(phone)) {
			throw new MobException("phone");
		}
		if (StringUtils.isBlank(password)) {
			throw new MobException("password");
		}
		if (StringUtils.isBlank(device)) {
			throw new MobException("device");
		}

		//校验登录
		User user = userService.getUserByUsernameAndPassword(phone, password);
		
		if(user==null){
			throw new MobException(MEnumError.LOGIN_FAILURE_ERROR);
		}
		 
		//禁用
		if(user.getState() == 0){
			throw new MobException(MEnumError.ACCOUNT_STOP_ERROR);
		}
		
		mobileInfo.setUserid(user.getId()+"");
		String verify = mobileVerifyService.updateMobileVerify(mobileInfo, device, cid, true);
		
		// 返回
		MAccount.Builder ret = MAccount.newBuilder();
		ret.setId(user.getId()+"");
		ret.setVerify(verify);
		return ret;
	}

	/**
	* @api 第三方登录
	* @param type 1:qq 2:sina
	* @param openid openid
	* @param accessToken accessToken
	* @param device 设备类型  android或ios
	* @param cid //个推cid
	* @url /mobile?methodno=MOauthLogin&debug=1&deviceid=test&type=&openid=&accessToken=&device=
	*/
/*	@RequestMapping("mOauthLogin")
	@MobileMethod
	public MAccount.Builder oauthLogin(MobileInfo mobileInfo, Integer type, String openid, String accessToken, String device,String cid) throws Exception {
		// 参数校验
		if (type==null) {
			throw new MobException("type");
		}
		if (StringUtils.isBlank(openid)) {
			throw new MobException("openid");
		}
		if (StringUtils.isBlank(accessToken)) {
			throw new MobException("accessToken");
		}
		if (StringUtils.isBlank(device)) {
			throw new MobException("device");
		}
		
////		UserOauthExample example = new UserOauthExample();
////		example.createCriteria().andTypeEqualTo(type).andOpenIdEqualTo(openid);
////		List<UserOauth> list = oauthService.selectByExample(example);
////		
////		User user = null;
////		boolean insert = false;//是否需要添加
////		
////		if(list.size()>0){
////			UserOauth oauth = list.get(0);
////			user = userService.selectByPrimaryKey(oauth.getUserId());
////			if(user == null){
////				oauthService.deleteByPrimaryKey(oauth.getId());
////				insert = true;
////			}else if(user.getState() == 0){
////				throw new MobException(MEnumError.ACCOUNT_STOP_ERROR);
////			}
////		}else{
////			insert = true;
////		}
//		
//		//插入
//		if(insert){
//			//添加数据
//			Date date = new Date();
//			String accout = DateUtil.dateToStr(date, "yyyyMMddHHmmss");
//			if(type == 1){
//				accout = "qq_"+accout;
//			}else if(type == 2){
//				accout = "sina_"+accout;
//			}else if(type == 3){
//				accout = "wx_"+accout;
//			}
//			user = new User();
//			user.setId(randomCodeService.getRandom());
//			user.setCreateTime(date);
//			user.setCredit(0);
//			user.setState(1);
//			user.setBalance(BigDecimal.ZERO);
//			user.setNickName("匿名用户");
//			user.setSex(0);
//			user.setBannedPost(0);
//			user.setCreditCnt(0);
//			user.setVip(0);
//			user.setAccount(accout);
//			
//			if (type == 1 || type == 2){
//				//百度获取第三方登录信息
//				BaiduSocial social = BaiduSocialUtil.getUserInfo(accessToken);
//				
//				if (social != null){
//					user.setNickName(social.getUsername());
//					
//					try {
//						user.setSex(Integer.parseInt(social.getSex()));
//					} catch (NumberFormatException e) {
//						e.printStackTrace();
//					}
//					
//					if (social.getHeadurl() != null){
//						user.setHeadImg(uploadHeadImg(social.getHeadurl()));
//					}
//				}else{
//					throw new MobException(MEnumError.OAUTHLOGIN_FAILURE_ERROR);
//				}
//			}else if (type == 3){
//				WxOauth social = BaiduSocialUtil.getUserInfo(accessToken, openid);
//				
//				if (social != null){
//					user.setNickName(social.getNickName());
//					
//					user.setSex(user.getSex() == 0 ? 3 : user.getSex());
//					
//					if (social.getHeadimgurl() != null){
//						user.setHeadImg(uploadHeadImg(social.getHeadimgurl()));
//					}
//				}else{
//					throw new MobException(MEnumError.OAUTHLOGIN_FAILURE_ERROR);
//				}
//			}
//			
//			//保存
//			int cnt = userService.insert(user);
//			if(cnt == 0){
//				throw new MobException(MEnumError.CREATE_ACCOUNT_ERROR);
//			}
//			
//			//保存第三方登录信息
//			UserOauth oauth = new UserOauth();
//			oauth.setAccessToken(accessToken);
//			oauth.setCreateTime(new Date());
//			oauth.setOpenId(openid);
//			oauth.setType(type);
//			oauth.setUserId(user.getId());
//			cnt = oauthService.insert(oauth);
//			if(cnt == 0){
//				throw new MobException(MEnumError.CREATE_ACCOUNT_ERROR);
//			}
//		}
//		
//		//更新登录验证
//		mobileInfo.setUserid(user.getId());
//		String verify = verifyService.updateMobileVerify(mobileInfo, device, cid, MULTI_LOGIN);
		
		//返回
		MAccount.Builder ret = MAccount.newBuilder();
//		ret.setId(user.getId());
//		ret.setVerify(verify);
		return ret;
	}*/
	
	/**
	 * 第三方登录获取头像
	 * @param url
	 * @return
	 * @throws Exception
	 */
//	private String uploadHeadImg(String url){
//		try {
//			String savePath = UUID.randomUUID().toString();
//			byte[] bytes = BaiduSocialUtil.download(url);
//			
//			FileType type = BaiduSocialUtil.getType(Arrays.copyOf(bytes, 28));
//			if (type != null)
//				savePath += "."+type.name().toLowerCase();
//			
//			String img = fileService.uploadFile(bytes, savePath, null);
//			return img;
//		} catch (Exception e) {
//			return null;
//		}
//	}

//	/**
//	 * 完善资料
//	 * @param nickName 昵称
//	 * @param headImg 头像ID
//	 * @param sex 性别
//	 * @url /mobile?methodno=MUpdateUser&debug=1&userid=1&verify=1&deviceid=test&name=&headImg=
//	 */
//	@RequestMapping("mUpdateUser")
//	@MobileMethod
//	@LoginFilter(validateClz=MobileLoginValidate.class)
//	public MUser.Builder updateUser(MobileInfo mobileInfo, String nickName, String headImg,String sex) throws Exception {
//		//更新数据
//		User record = new User();
//		record.setId(mobileInfo.getUserid());
//		record.setNickName(nickName);
//		record.setHeadImg(headImg);
//		if(StringUtils.isNotBlank(sex))
//			record.setSex(Integer.parseInt(sex));
//		userService.updateByPrimaryKeySelective(record);
//		
//		// 返回
//		MUser.Builder ret = MUser.newBuilder();
//		User user = userService.selectByPrimaryKey(mobileInfo.getUserid());
//		if(user!=null){
//			ret.setId(user.getId());
//			ret.setHeadImg(StringUtil.emptyIfBlank(user.getHeadImg()));
//			ret.setNickName(StringUtil.emptyIfBlank(user.getNickName()));
//			ret.setSex(user.getSex());
//		}
//		return ret;
//	}

	/**
	 * 忘记密码
	 * @param phone 手机号
	 * @param code 验证码
	 * @param password 密码(需要加密)
	 * @param device //设备类型  android或ios
	 * @param cid //个推cid
	 * @url /mobile?methodno=MForgetPassword&debug=1&deviceid=test&phone=&code=&password=&pushId=&device=
	 */
	@RequestMapping("mForgetPassword")
	@MobileMethod
	public MAccount.Builder forgetPassword(MobileInfo mobileInfo, String phone, 
			String code, String password, String device, String cid) throws Exception {
		// 参数校验
		if (StringUtils.isBlank(phone)) {
			throw new MobException("phone");
		}
		if (StringUtils.isBlank(code)) {
			throw new MobException("code");
		}
		if (StringUtils.isBlank(password)) {
			throw new MobException("password");
		}
		if (StringUtils.isBlank(device)) {
			throw new MobException("device");
		}

		//验证码验证
		String value = CacheSupport.get("mobileCodeCache", phone, String.class);
		if(!code.equals(value)){
			throw new MobException(MEnumError.MOBILE_CODE_ERROR);
		}
		
		//修改数据
		Page<User> users = userService.findByPhone(phone,new PageRequest(0, 1));
		
		if(users.getContent().size() == 0){
			throw new MobException(MEnumError.PHONE_NOTEXISTS_ERROR);
		}
		
		//更新用户名密码
		User record = users.iterator().next();
		record.setPassword(password);
		userService.updatePassword(phone, password);
		
		mobileInfo.setUserid(record.getId()+"");
		String verify = mobileVerifyService.updateMobileVerify(mobileInfo, device, cid, true);
		
		// 返回
		MAccount.Builder ret = MAccount.newBuilder();
		ret.setId(record.getId()+"");
		ret.setVerify(verify);
		return ret;
	}

	/**
	 * 修改密码
	 * @param oldPwd 旧密码(需要加密)
	 * @param newPwd 新密码(需要加密)
	 * @url /mobile?methodno=MChangePassword&debug=1&userid=1&verify=1&deviceid=test&oldPwd=&newPwd=
	 */
	@RequestMapping("mChangePassword")
	@MobileMethod
	@LoginFilter(validateClz=MobileLoginValidate.class)
	public MRet.Builder changePassword(MobileInfo mobileInfo, String oldPwd, String newPwd) throws Exception {
		// 参数校验
		if (StringUtils.isBlank(newPwd)) {
			throw new MobException("newPwd");
		}
		if (StringUtils.isBlank(oldPwd)) {
			throw new MobException("oldPwd");
		}
//		
		User user = userService.findByPrimaryKey(mobileInfo.getUserid());
		if(!oldPwd.equals(user.getPassword())){
			throw new MobException(MEnumError.PASSWORD_FALSE_ERROR);
		}
		
//		//删除其他设备的登录验证信息
//		MobileVerifyExample example = new MobileVerifyExample();
//		example.createCriteria().andUserIdEqualTo(mobileInfo.getUserid()).andDeviceIdNotEqualTo(mobileInfo.getDeviceid());
//		verifyService.deleteByExample(example);
//		
//		//更新数据
//		User record = new User();
//		record.setId(mobileInfo.getUserid());
//		record.setPassword(newPwd);
//		userService.updateByPrimaryKeySelective(record);
		
		// 返回
		MRet.Builder ret = MRet.newBuilder();
		ret.setCode(0);
		return ret;
	}

	/**
	 * 注销
	 * @url /mobile?methodno=MLogout&debug=1&userid=1&verify=1&deviceid=test&oldPwd=&newPwd=
	 */
	@RequestMapping("mLogout")
	@MobileMethod
	@LoginFilter(validateClz=MobileLoginValidate.class)
	public MRet.Builder logout(MobileInfo mobileInfo) throws Exception {
		mobileVerifyService.logout(mobileInfo);
		MRet.Builder ret = MRet.newBuilder();
		ret.setCode(0);
		return ret;
	}

	/**
	* @api 绑定手机
	* @param phone 手机号
	* @param password 密码
	* @param code 短信验证码
	* @url /mobile?methodno=MBindPhone&debug=1&deviceid=test&userid=&verify=&phone=&code=
	*/
	@RequestMapping("mBindPhone")
	@MobileMethod
	@LoginFilter(validateClz=MobileLoginValidate.class)
	public MRet.Builder bindPhone(MobileInfo mobileInfo,String phone,String password,String code) throws Exception {
		// 参数校验
		if (StringUtils.isBlank(phone)) {
			throw new MobException("phone");
		}
		if (StringUtils.isBlank(code)) {
			throw new MobException("code");
		}
		
		User user = userService.findByPrimaryKey(mobileInfo.getUserid());
		
		//验证码验证
		String value = CacheSupport.get("mobileCodeCache", phone, String.class);
		if(!code.equals(value)){
			throw new MobException(MEnumError.MOBILE_CODE_ERROR);
		}
		
//		user.setAccount(phone);
//		user.setPassword(password);
//		userService.updateByPrimaryKeySelective(user);
		
		MRet.Builder ret = MRet.newBuilder();
		ret.setCode(0);
		return ret;
	}
	
	/**
	 * 获取用户信息
	 * @param id		//id
	 * @url /mobile?methodno=MGetUserInfo&debug=1&deviceid=test&appid=1&content=
	 */
	@RequestMapping("mUserInfo")
	@MobileMethod
	@LoginFilter(validateClz=MobileLoginValidate.class)
	public MUserInfo.Builder getUserInfo(MobileInfo mobileInfo) throws Exception{
		
		User user = userService.findByPrimaryKey(mobileInfo.getUserid());
		if(user == null || user.getState() == 0)throw new MobException(MEnumError.USER_NOT_EXISTS);
		
		MUserInfo.Builder ret = MUserInfo.newBuilder();
		ret.setHeadImg(user.getImage());
		ret.setNickName(user.getNickName());
		ret.setSex(user.getSex());
		ret.setCredit(user.getCredit().toString());
		ret.setQrMsg(properityUtil.getSelf_url()+"/m/register?phone="+user.getUsername());
		return ret;
	}
	
}
